package com.hbt.myplus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.hbt.myplus.service.impl.RegServiceImpl;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.hbt.myplus.service.IPetService;
import com.hbt.myplus.service.impl.PetServiceImpl;
import com.hbt.myplus.model.Pet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hbt.myplus.utils.ResponseWeb;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
    * 宠物 前端控制器
    * </p>
 *
 * @author astupidcoder
 * @since 2020-12-22
 * @version v1.0
 */
@RestController
@RequestMapping("pet")


public class PetController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private PetServiceImpl petService;

    @Autowired
    private RegServiceImpl regService;
    /**
     * 查询分页数据
     */
    @GetMapping(value = "/s")
    public ResponseWeb<Page> findListByPage(@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,@RequestParam(name = "pageSize", defaultValue = "20") int pageSize){
        return null;
    }

    @GetMapping(value = "/all")
    public ResponseWeb<List<Pet>> getAllByOpenId(@RequestHeader("openid") String openid){

        return new ResponseWeb<>(petService.list(new QueryWrapper<Pet>().eq("delete_flag", 0).eq("openid", openid)));
    }

    /**
     * 根据id查询
     */
    @GetMapping(value = "/{id}")
    public ResponseWeb<Pet> getById(@PathVariable("id") String id){
       return new ResponseWeb<>(petService.getById(id));
    }

    /**
     * 根据id查询
     */
    @GetMapping(value = "reg/{reg_id}")
    public ResponseWeb<Pet> getByRegId(@PathVariable("reg_id") String reg_id){

        return new ResponseWeb(petService.getById(regService.getById(reg_id).getPetId()));
    }


    /**
     * 新增
     */
    @PostMapping
    public ResponseWeb<Pet> add(@RequestBody Pet pet, @RequestHeader("openid")String openid){
        pet.setOpenid(openid);
        return new ResponseWeb(petService.save(pet));
    }

    /**
     * 删除
     */
    @GetMapping
    public ResponseWeb<String> delete(@RequestParam("id") int id){
        Pet petOld = petService.getById(id);
        if (petOld == null){
            return ResponseWeb.fail("删除失败");
        }
        petOld.setDelete_flag(1);
        if (petService.updateById(petOld)){
            return new ResponseWeb("删除成功");
        }
        return ResponseWeb.fail("删除失败");
    }

    /**
     * 修改
     */
    @PutMapping
    public ResponseWeb<Pet> update(@RequestBody Pet pet){

        return new ResponseWeb(petService.updateById(pet));
     }

}
